package cn.tedu.csmall.resource.controller;

import cn.tedu.csmall.commons.exception.ServiceException;
import cn.tedu.csmall.commons.response.ServiceCode;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static cn.tedu.csmall.commons.response.ServiceCode.NOT_ACCEPTABLE;

@RestController
@RequestMapping("/upload")
@Api(tags = "上传模块")
public class FileUploadController {

    @Value("${csmall.file-upload.base-dir}")
    private String baseDir;

    @PostMapping("/avatar")
    public String uploadAvatar(MultipartFile file) throws IOException {
        String targetParentDirName = "avatar";
        String targetSubDirName = generateDirNameByDate();
        List<String> contextTypes = new ArrayList<>();
        contextTypes.add("image/jpeg");
        contextTypes.add("image/png");
        long maxSize = 500 * 1024;
        upload(file,maxSize, contextTypes,targetParentDirName,targetSubDirName);
        return "OK";
    }

    @PostMapping("/brand-icon")
    public String uploadBrandIcon(MultipartFile file,String brandPinyin) throws IOException {
        String targetParentDirName = "brand-icon";
        List<String> contextTypes = new ArrayList<>();
        contextTypes.add("image/png");
        long maxSize = 100 * 1024;
        upload(file,maxSize, contextTypes,targetParentDirName,brandPinyin);
        return "OK";
    }


    public String upload(MultipartFile file, long maxSize,List<String> contextTypes, String targetParentDirName, String targetSubDirName) throws IOException {
        // 判断是否存在上传数据
        if(file == null || file.isEmpty()){
            throw new ServiceException(ServiceCode.NOT_ACCEPTABLE,"上传失败,请选择正确的文件再提交");
        }

        // 判断文件大小是否超出了限制
        if (file.getSize() > maxSize) {
            throw new ServiceException(NOT_ACCEPTABLE, "上传失败，文件大小超出了限制（最大" + maxSize / 1024 + "KB）！");
        }


        //判断文件MIME类型,比如:image/jpeg
        String contextType = file.getContentType();
        if(!contextTypes.contains(contextType)){
            throw new ServiceException(ServiceCode.NOT_ACCEPTABLE,"上传失败,不支持"+contextType+"类型的文件上传,支持的类型有"+contextTypes);
        }

        //上传的文件夹
        File targetParentDir = new File(baseDir,targetParentDirName);
        File targetSubDir = new File(targetParentDir,targetSubDirName);
        if(!targetSubDir.exists()){
            targetSubDir.mkdirs();
        }
        // 上传的文件名
        String fileName = generateFileNameByTime()
                + "-" + System.nanoTime()
                + "-" + getRandomValue();

        // 上传的扩展名
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(i);
        // 上传的文件的全名
        String fileFullName = fileName+suffix;
        File dest = new File(targetSubDir,fileFullName);
        file.transferTo(dest);
        return "OK";
    }

    /**
     * 用于格式化日期的工具对象
     */
    private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    /**
     * 用于格式化日期的工具对象
     */
    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    /**
     * 根据日期生成文件夹名称
     * @return 当前日期对应的文件夹名称
     */
    public String generateDirNameByDate(){
        LocalDateTime now = LocalDateTime.now();
        return dateFormatter.format(now);
    }

    public String generateFileNameByTime(){
        LocalDateTime now = LocalDateTime.now();
        return dateTimeFormatter.format(now);
    }

    private Random random = new Random();

    private Integer getRandomValue(){
        return random.nextInt(900000)+100000;
    }
}
